package com.woniu.woniu_bx.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.woniu.woniu_bx.pojo.Goods;
import com.woniu.woniu_bx.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author : 王泰元
 * @className: GoodsMapper
 * @description: TODO
 * @date : 2022/8/27 16:19
 */
@Repository
public interface GoodsMapper extends BaseMapper<Goods> {
    /**
     * 多条件查询商品信息
     * @param goods
     * @return
     */
    @SelectProvider(type = GoodsMapper.GoodsSqlProvider.class, method = "select")
    @Results(id = "goodsMap", value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "account", property = "user.account"),
            @Result(column = "name", property = "goodsCategory.name"),
            @Result(column = "nick", property = "user.nick"),
            @Result(column = "voice", property = "voice"),
            @Result(column = "description", property = "description"),
            @Result(column = "money", property = "money"),
            @Result(column = "sale_num", property = "saleNum"),
            @Result(column = "status", property = "status"),
            @Result(column = "auth_goods", property = "authGoods")
    })
    List<Goods> getByCondition(Goods goods);

    //随机查询3条记录
    @Select("select * from bx_goods order by rand() limit 0,3")
    @Results({
            @Result(column = "id",property = "id"),
            @Result(column = "user_id",property = "user",many=@Many(select="com.woniu.woniu_bx.mapper.UserMapper.findByUserId"))
    })
    List<Goods> findByRandom();

    /**
     * 动态更新商品信息
     * 接单数、用户id不允许修改
     * @param goods
     */
    @UpdateProvider(type = GoodsMapper.GoodsSqlProvider.class, method = "update")
    void update(Goods goods);

    /**
     * 根据 id 逻辑删除商品
     *
     * @param id 角色的 id
     */
    @Delete("update bx_goods set status = 'n' where id = #{id}")
    void delete(int id);

    /**
     * 根据商品id查询出商品所属的类别
     * @param id 商品id
     */
    @Select("select c.name cnmae,g.description,g.money,g.sale_num,user_id from bx_category c,bx_goods g where c.id = g.category_id and g.id = #{id}")
    @Results(
            {
                    @Result(column = "description", property = "description"),
                    @Result(column = "money", property = "money"),
                    @Result(column = "sale_num", property = "saleNum"),
                    @Result(column = "cnmae", property = "goodsCategory.name"),
                    @Result(column = "user_id", property = "userId")
            }
    )
    Goods findCategoryById(int id);


    @Update("update bx_goods set status = #{status} where id = #{id}")
    void updateStatus( @Param("id")Integer id,  @Param("status")String status);

    @Select("select url from bx_goods_img where goods_id = #{id}")
    List<String> getGoodsImagesById(Integer id);

    @Select("select * from bx_goods where user_id=#{userId} and status!='d'")
    @Results({
            @Result(property = "user",column = "user_id",one = @One(select="com.woniu.woniu_bx.mapper.UserMapper.getUserById")),
            @Result(property = "goodsCategory",column = "category_id",one = @One(select="com.woniu.woniu_bx.mapper.GoodsCategoryMapper.findCategoryById"))
    })
    List<Goods> getGoodsListByUserId(Integer userId);
    @Select("select * from bx_goods where user_id=#{userId} and status=#{status}")
    @Results({
            @Result(property = "user",column = "user_id",one = @One(select="com.woniu.woniu_bx.mapper.UserMapper.getUserById")),
            @Result(property = "goodsCategory",column = "category_id",one = @One(select="com.woniu.woniu_bx.mapper.GoodsCategoryMapper.findCategoryById"))
    })
    List<Goods> getGoodsListByUserIdAndStatus(@Param("userId") Integer userId, @Param("status") String status);

    /**
     * sql 语句构建器；
     * 根据传入的 goods（封装了条件）、method，产生并返回对应的动态 sql 语句
     */
    @Slf4j
    public static class GoodsSqlProvider {
        public String update(Goods goods) {
            return new SQL() {
                {
                    UPDATE("bx_goods");
//                    if (goods.getGoodsCategory().getId() != null) {
//                        SET("category_id=#{categoryId}");
//                    }
                    if (StringUtils.hasLength(goods.getVoice())) {
                        SET("voice=#{voice}");
                    }
                    if (StringUtils.hasLength(goods.getDescription())) {
                        SET("description=#{description}");
                    }
                    if (goods.getMoney() != null) {
                        SET("money=#{money}");
                    }
                    if (goods.getSaleNum() != null) {
                        SET("sale_num=#{saleNum}");
                    }
                    if (StringUtils.hasLength(goods.getStatus())) {
                        SET("status=#{status}");
                    }
                    if (StringUtils.hasLength(goods.getAuthGoods())) {
                        SET("auth_goods=#{authGoods}");
                    }
                    WHERE("id=#{id}");
                }
            }.toString();
        }

        /**
         * 得到动态产生的多条件查询 sql 语句
         *
         * @param goods
         * @return 动态产生的 sql 查询语句
         */
        public String select(Goods goods) {
            return new SQL() {
                {
                    SELECT("g.id","account","nick","`name`","voice","description","g.money","sale_num","g.status","g.auth_goods");
                    FROM("bx_goods g");
                    JOIN("bx_user u on g.user_id=u.id");
                    LEFT_OUTER_JOIN("bx_category c on g.category_id=c.id");
                    if (goods.getUser() != null && goods.getUser().getAccount() != null) {
                        WHERE("account like CONCAT('%',#{user.account},'%')");
                    }
                    if (goods.getUser() != null && goods.getUser().getNick() != null) {
                        WHERE("nick like CONCAT('%',#{user.nick},'%')");
                    }
                    if (goods.getGoodsCategory() != null && goods.getGoodsCategory().getName() != null) {
                        WHERE("`name` like CONCAT('%',#{goodsCategory.name},'%')");
                    }
                    if (StringUtils.hasLength(goods.getVoice())) {
                        WHERE("voice=#{voice}");
                    }
                    if (StringUtils.hasLength(goods.getDescription())) {
                        WHERE("description=#{description}");
                    }
                    if (goods.getMoney() != null) {
                        WHERE("g.money=#{money}");
                    }
                    if (goods.getSaleNum() != null) {
                        WHERE("sale_num > #{saleNum}");
                    }
                    if (StringUtils.hasLength(goods.getStatus())) {
                        SET("g.status=#{status}");
                    }
                    if (StringUtils.hasLength(goods.getAuthGoods())) {
                        SET("auth_goods=#{authGoods}");
                    }
                }
            }.toString();
        }
    }
}
